package com.genghis.ptas.web;

import com.genghis.core.captcha.RandomImage;
import com.genghis.core.captcha.impl.RandomImageImpl;
import com.genghis.ptas.security.entity.User;
import com.genghis.ptas.security.service.RoleService;
import com.genghis.ptas.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

/**
 * @author gaoxinyu
 * @version 1.0.1
 */
@Controller
@RequestMapping("/")
public class HomeController {
    @Autowired
    private UserService userService;

    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    public String index(HttpServletRequest request) {
        return userService.returnIndexPage(request);
    }

    @RequestMapping("lock_screen.*")
    public String displayLockScreenPage(HttpServletRequest request) {
        String loginName = request.getParameter("loginName");
        User user = userService.findFullUserByUserLoginName(loginName);
        request.setAttribute("user", user);
        return "lockScreen";
    }

    @RequestMapping(value = "captcha",  method = {RequestMethod.GET, RequestMethod.POST})
     public void viewCaptcha(HttpServletRequest request, HttpServletResponse response)throws  IOException {
        RandomImage randomImage = new RandomImageImpl();
        HttpSession session = request.getSession();
        session.setAttribute("validation_code", randomImage.getValidateString());//将验证码保存在session中
        //关闭客户端浏览器的缓冲区。
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        OutputStream os = response.getOutputStream();//得到输出流
        ImageIO.write(randomImage.getValidateImage(), "JPEG", os);
    }

    /**
     * 验证码判断
     *
     * @param request
     * @param captcha//输入的验证码
     * @return boolean
     * @since Ver 2.0.0
     */
    @RequestMapping(value = "verifyCaptcha", method = RequestMethod.POST)
    @ResponseBody
    public boolean verifyCaptcha(@RequestParam("validateCode") String captcha, HttpServletRequest request) throws Exception {
        try {
            return (request.getSession().getAttribute("validation_code").toString()).equals(captcha);
        } catch (Exception e) {
            return false;
        }
    }

}